import 'dart:async';
import 'dart:convert';

import 'package:dingtalk/core/blocs/chat/chat_bloc.dart';
import 'package:dingtalk/core/events/message_event.dart';
import 'package:dingtalk/core/model/chat_model.dart';
import 'package:dingtalk/core/utils/event_bus_util.dart';
import 'package:dingtalk/core/values/values.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import 'chat_item_view.dart';

class THChatScreen extends StatefulWidget {
  static final String routeName = "chatScreen";

  final String currentChatUserId;

  final String currentChatUserName;

  THChatScreen({this.currentChatUserId, this.currentChatUserName});

  @override
  _THChatScreenState createState() => _THChatScreenState();
}

class _THChatScreenState extends State<THChatScreen> {
  TextEditingController _chatMessageController;

  StreamSubscription _subscription;

  ScrollController _scrollController;

  @override
  void initState() {
    super.initState();
    BlocProvider.of<THChatBloc>(context)..add(THChatMessageListEvent());

    _scrollController = ScrollController();

    _chatMessageController = TextEditingController(text: "云想衣裳花想容，春风拂槛露华浓。");

    _subscription =
        EventBusUtil.getInstance().on<THMessageEvent>().listen((event) {
      String fromUserId = json.decode(event.message)['fromUserId'];
      print('接收到消息 :: ${event.message}');
//      if (fromUserId.isNotEmpty && fromUserId == widget.currentChatUserId) {
//        THChatModel chatModel = THChatModel(
//          userId: widget.currentChatUserId,
//          userName: widget.currentChatUserName,
//          isSend: 0,
//          time: 1599123628389,
//          message: json.decode(event.message)['content'],
//          type: json.decode(event.message)['type'],
//        );
//
//        BlocProvider.of<THChatBloc>(context)
//          ..add(THChatReceiverMessageEvent(chatModel: chatModel));
//        _scrollToBottom();
//      }
    });
  }

  _sendTextMessage() {
    String content = _chatMessageController.text;
    if (content.isEmpty) return;

    BlocProvider.of<THChatBloc>(context)
      ..add(THChatSendMessageEvent(
          targetId: widget.currentChatUserId, content: content));

    _chatMessageController.text = "";
    setState(() {});

    _scrollToBottom();
  }

  _scrollToBottom() {
    _scrollController.animateTo(_scrollController.position.maxScrollExtent,
        duration: const Duration(milliseconds: 350), curve: Curves.easeOut);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          widget.currentChatUserName,
          style: TextStyle(color: kColor33),
        ),
      ),
      body: BlocBuilder<THChatBloc, THChatState>(
        builder: (context, THChatState state) {
          if (state is THChatListState) {
            List<THChatModel> chatItemList = state.chatList;
            return ListView.builder(
                shrinkWrap: true,
                controller: _scrollController,
                itemCount: null == chatItemList ? 0 : chatItemList.length,
//                physics: NeverScrollableScrollPhysics(),
                itemBuilder: (BuildContext context, int index) {
                  THChatModel model = chatItemList[index];
                  return THChatItemView(model: model);
                });
          }
          return Container();
        },
      ),
      bottomNavigationBar: SafeArea(
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: kSize20),
          decoration: BoxDecoration(boxShadow: []),
          child: Row(
            children: [
              Container(
                  child: Text("语音"), padding: EdgeInsets.only(left: kSize20)),
              Expanded(
                  child: Container(
                margin: EdgeInsets.symmetric(horizontal: kSize20),
                decoration: BoxDecoration(
                  boxShadow: [BoxShadow(color: kTHNormal)],
                  borderRadius: BorderRadius.all(Radius.circular(kSize50)),
                ),
                child: TextField(
                    controller: _chatMessageController,
                    decoration: InputDecoration(
                        contentPadding: EdgeInsets.all(kSize20),
                        border: InputBorder.none,
                        isDense: true)),
              )),
              GestureDetector(
                onTap: _sendTextMessage,
                child: Container(
                    child: Text("发送"),
                    padding: EdgeInsets.only(right: kSize20)),
              ),
            ],
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    if (null != _subscription) {
      _subscription.cancel();
    }
    super.dispose();
  }
}
